package com.ruoyi.law.controller;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.PageCondition;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.law.domain.dto.LawOrderDTO;
import com.ruoyi.law.domain.dto.LawTeamDTO;
import com.ruoyi.law.domain.entity.LawLawyer;
import com.ruoyi.law.domain.entity.LawOrder;
import com.ruoyi.law.domain.entity.LawService;
import com.ruoyi.law.domain.entity.LawTeam;
import com.ruoyi.law.service.*;
import com.ruoyi.law.utils.UserUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author code
 * @since 2022-11-30
 */
@Api(tags = "团队管理")
@RestController
@RequestMapping("/team")
public class LawTeamController extends BaseController {

    @Autowired
    private ILawTeamService teamService;
    @Autowired
    private ILawTeamServiceService teamServiceRelation;
    @Autowired
    private ILawServiceService serviceService;
    @Autowired
    private ILawLawyerService lawyerService;
    @Autowired
    private ILawOrderService orderService;

    @Anonymous
    @ApiOperation("列表")
    @GetMapping("/list")
    public R<Page<LawTeamDTO>> list(PageCondition<LawTeam> pageCondition) {
        Page<LawTeam> page = teamService.page(pageCondition.toPage());
        List<LawTeamDTO> list = new ArrayList<>();
        page.getRecords().forEach(team -> {
            LawTeamDTO lawTeamDTO = BeanUtil.toBean(team, LawTeamDTO.class);
            // 律师申请信息
            LawLawyer lawLawyer = lawyerService.getById(team.getLawyarId());
            lawTeamDTO.setLawLawyer(lawLawyer);
            list.add(lawTeamDTO);
        });
        Page<LawTeamDTO> pageDTO = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());
        pageDTO.setRecords(list);
        return R.ok(pageDTO);
    }

    @Anonymous
    @ApiOperation("详情")
    @GetMapping("/info")
    public R<LawTeamDTO> info(Long id) {
        LawTeamDTO lawTeamDTO = teamService.getDtoById(id);
        return R.ok(lawTeamDTO);
    }

    @Anonymous
    @ApiOperation("根据用户id查询")
    @GetMapping("/infoByUserId")
    public R<LawTeamDTO> infoByUserId(Long userId) {
        LambdaQueryWrapper<LawTeam> queryWrapper = new LambdaQueryWrapper<>();
        LawTeam team = teamService.getOne(queryWrapper.eq(LawTeam::getUserId, userId), false);
        if (team == null) {
            return R.fail("未找到该用户的律师信息");
        }
        LawTeamDTO lawTeamDTO = teamService.getDtoById(team.getId());
        return R.ok(lawTeamDTO);
    }

    @ApiOperation("查询当前律师的订单")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderState", value = "订单状态((0:未支付，1:已支付(进行中),2:已完成))"
                    , paramType = "query", dataType = "String"),
    })
    @GetMapping("/getLawyerOrder")
    public R<Page<LawOrderDTO>> getLawyerOrder(PageCondition<LawOrder> pageCondition, String orderState) {
        Long userId = getUserId();
        LambdaQueryWrapper<LawTeam> teamQueryWrapper = new LambdaQueryWrapper<>();
        teamQueryWrapper.eq(LawTeam::getUserId, userId);
        LawTeam team = teamService.getOne(teamQueryWrapper, false);
        Assert.notNull(team, "该用户不是律师！");

        LambdaQueryWrapper<LawOrder> orderQueryWrapper = new LambdaQueryWrapper<>();
        orderQueryWrapper.eq(LawOrder::getLawyerId, team.getId());
        orderQueryWrapper.eq(StrUtil.isNotBlank(orderState), LawOrder::getState, orderState);
        Page<LawOrder> page = orderService.page(pageCondition.toPage(), orderQueryWrapper);
        List<LawOrder> records = page.getRecords();

        List<LawOrderDTO> lawOrderDTOs = new ArrayList<>();
        for (LawOrder lawOrder : records) {
            LawOrderDTO lawOrderDTO = BeanUtil.toBean(lawOrder, LawOrderDTO.class);
            Long uid = lawOrder.getUid();
            lawOrderDTO.setUserName(UserUtil.getUserName(uid));
            lawOrderDTO.setUserId(uid);
            lawOrderDTO.setConsultingName(serviceService.getById(lawOrder.getConsultingId()).getTitle());

            SysUser user = UserUtil.getUser(uid);
            String fillInPhone = lawOrder.getFillInPhone();
            fillInPhone = StrUtil.isBlank(fillInPhone) ? user.getPhonenumber() : fillInPhone;
            lawOrderDTO.setFillInPhone(fillInPhone);
            lawOrderDTO.setAvatar(user.getAvatar());
            lawOrderDTOs.add(lawOrderDTO);
        }

        Page<LawOrderDTO> pageDTO = new Page<>(page.getCurrent(), page.getSize(), page.getTotal());
        pageDTO.setRecords(lawOrderDTOs);
        return R.ok(pageDTO);
    }

    @ApiOperation("根据订单id修改订单状态")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderState", value = "订单状态((0:未支付，1:已支付(进行中),2:已完成))"
                    , paramType = "query", dataType = "String"),
            @ApiImplicitParam(name = "orderId", value = "订单id", paramType = "query", dataType = "String"),
    })
    @GetMapping("/changeOrderState")
    public R<String> changeOrderState(String orderId, String orderState) {
        LambdaUpdateWrapper<LawOrder> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(LawOrder::getId, orderId);
        updateWrapper.set(LawOrder::getState, orderState);
        boolean update = orderService.update(updateWrapper);
        return update ? R.ok() : R.fail();
    }

    @ApiOperation("新增")
    @PostMapping("/save")
    public R<Object> save(@RequestBody LawTeamDTO lawTeamDTO) {
        boolean saveDto = teamService.saveDto(lawTeamDTO);
        return saveDto ? R.ok() : R.fail();
    }

    @ApiOperation("修改")
    @PostMapping("/update")
    public R<Object> update(@RequestBody LawTeamDTO lawTeamDTO) {
        boolean updateDto = teamService.updateDto(lawTeamDTO);
        return updateDto ? R.ok() : R.fail();
    }

    @ApiOperation("删除")
    @PostMapping("/delete")
    public R<Object> delete(@RequestBody Long id) {
        boolean remove = teamService.removeById(id);
        teamServiceRelation.removeByTeamId(id);
        return remove ? R.ok() : R.fail();
    }

    @ApiOperation("查询服务范围数据")
    @GetMapping("/getTeamService")
    public R<List<Map<String, Object>>> getTeamService() {
        List<LawService> serviceList = serviceService.list();

        List<Map<String, Object>> resList = serviceList.stream().map(service -> {
            Map<String, Object> map = new HashMap<>(2);
            map.put("id", service.getId());
            map.put("name", service.getTitle());
            return map;
        }).collect(ArrayList::new, ArrayList::add, ArrayList::addAll);
        return R.ok(resList);
    }

}
